import React, { Component } from 'react';
import PubSub from 'pubsub-js';
import axios from 'axios';
export default class Search extends Component {
  searchUsers = (event) => {
    if (event.key === 'Enter' || event.type === 'click') {
      // 阻止默认行为，防止提交表单
      event.preventDefault();
      // 获取用户输入(连续解构赋值+重命名)
      const {
        keywordElement: { value: keyword },
      } = this;
      // 发送请求前通知List更新状态
      PubSub.publish('search_user', { isFirst: false, isLoading: true });
      // 发送请求
      axios.get(`/api/search/users?q=${keyword}`).then(
        (response) => {
          // 请求成功后通知List更新状态
          PubSub.publish('search_user', {
            isLoading: false,
            users: response.data.items,
          });
        },
        (error) => {
          // 请求失败后通知List更新状态
          PubSub.publish('search_user', {
            isLoading: false,
            err: error.message,
          });
        }
      );
    }
  };
  render() {
    return (
      <section className='jumbotron' style={{ padding: '20px' }}>
        <h3 className='jumbotron-head'>搜索Github用户</h3>
        <div>
          <input
            type='text'
            ref={(c) => (this.keywordElement = c)}
            placeholder='输入关键字进行搜索'
            onKeyDown={this.searchUsers}
          />
          &nbsp;
          <button onClick={this.searchUsers}>搜索</button>
        </div>
      </section>
    );
  }
}
